// PWA管理器类，封装安装提示、推送通知和更新检测等能力

class PWAManager {
  private deferredPrompt: any = null;
  private updateAvailable = false;
  private registration: ServiceWorkerRegistration | null = null;

  constructor() {
    this.init();
  }

  private init() {
    // 监听beforeinstallprompt事件
    window.addEventListener('beforeinstallprompt', (e) => {
      // 阻止默认安装提示
      e.preventDefault();
      // 保存事件以便稍后触发
      this.deferredPrompt = e;
      // 显示自定义安装按钮
      this.showInstallPrompt();
    });

    // 监听appinstalled事件
    window.addEventListener('appinstalled', () => {
      console.log('PWA已安装');
      this.deferredPrompt = null;
      this.hideInstallPrompt();
    });

    // 注册Service Worker
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js')
          .then((registration) => {
            console.log('SW registered: ', registration);
            this.registration = registration;
            
            // 监听更新
            registration.addEventListener('updatefound', () => {
              const newWorker = registration.installing;
              if (newWorker) {
                newWorker.addEventListener('statechange', () => {
                  if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                    // 新版本可用
                    this.updateAvailable = true;
                    this.showUpdatePrompt();
                  }
                });
              }
            });
          })
          .catch((registrationError) => {
            console.log('SW registration failed: ', registrationError);
          });
      });
    }

    // 检查是否有更新
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      if (this.updateAvailable) {
        window.location.reload();
      }
    });
  }

  // 显示安装提示
  public showInstallPrompt() {
    // 这里可以触发自定义的安装提示UI
    console.log('可以安装PWA');
    // 示例：显示安装按钮
    // document.getElementById('install-button').style.display = 'block';
  }

  // 隐藏安装提示
  public hideInstallPrompt() {
    // 隐藏安装按钮
    // document.getElementById('install-button').style.display = 'none';
  }

  // 触发安装
  public async promptInstall() {
    if (!this.deferredPrompt) {
      return;
    }

    // 显示安装提示
    this.deferredPrompt.prompt();
    
    // 等待用户响应
    const { outcome } = await this.deferredPrompt.userChoice;
    
    if (outcome === 'accepted') {
      console.log('用户接受了安装提示');
    } else {
      console.log('用户拒绝了安装提示');
    }
    
    this.deferredPrompt = null;
  }

  // 显示更新提示
  public showUpdatePrompt() {
    // 这里可以触发自定义的更新提示UI
    console.log('有新版本可用');
    // 示例：显示更新按钮
    // document.getElementById('update-button').style.display = 'block';
  }

  // 触发更新
  public updateApp() {
    if (this.registration && this.registration.waiting) {
      // 向等待中的Service Worker发送消息
      this.registration.waiting.postMessage({ type: 'SKIP_WAITING' });
    }
    // 刷新页面以加载新版本
    window.location.reload();
  }

  // 请求推送通知权限
  public async requestNotificationPermission() {
    if (!('Notification' in window)) {
      console.log('此浏览器不支持通知');
      return false;
    }

    if (Notification.permission === 'granted') {
      console.log('通知权限已授予');
      return true;
    }

    if (Notification.permission !== 'denied') {
      const permission = await Notification.requestPermission();
      if (permission === 'granted') {
        console.log('通知权限已授予');
        return true;
      }
    }

    console.log('通知权限被拒绝');
    return false;
  }

  // 发送推送通知
  public async sendNotification(title: string, options: NotificationOptions = {}) {
    if (!this.registration) {
      console.log('Service Worker未注册');
      return;
    }

    try {
      await this.registration.showNotification(title, options);
    } catch (error) {
      console.error('发送通知失败:', error);
    }
  }
}

// 创建并导出PWA管理器实例
export const pwaManager = new PWAManager();